#include <SDL/SDL.h>

#include "keyboard.h"

Keyboard::Keyboard()
{
  memset(m_keys,0,sizeof(bool)*SDLK_LAST);
  memset(m_oldKeys,0,sizeof(bool)*SDLK_LAST);
}

Keyboard::~Keyboard()
{
}

void Keyboard::update()
{
  memcpy(m_keys,m_oldKeys,sizeof(bool)*SDLK_LAST);
}

void Keyboard::receiveEvent(const SDL_Event &sdl_event)
{
  // TODO Mirar si se reciben los eventos de las teclas modificadoras
  // en caso negativo anadir aqui las modificaciones a las teclas modificadoras
  // con SDLModState
  if(sdl_event.type!=SDL_KEYDOWN && sdl_event.type!=SDL_KEYUP)
    return;

  m_keys[sdl_event.key.keysym.sym]=(sdl_event.key.state==SDL_PRESSED);
}

bool Keyboard::isEventTriggered(const Event &event,Sint32& magnitude)
{
  if(event.peripheral!=Event::KEYBOARD)
    return false;

  if(event.component>SDLK_LAST || event.component<0)
    return false;

  switch(event.action)
  {
    case Event::ON_PRESS:
      if(m_keys[event.component] && !m_oldKeys[event.component])
      {
        magnitude=1;
        return true;
      }
      break;
    case Event::ON_PRESSING:
      if(m_keys[event.component])
      {
        magnitude=1;
        return true;
      }
      break;
    case Event::ON_RELEASE:
      if(!m_keys[event.component] && m_oldKeys[event.component])
      {
        magnitude=1;
        return true;
      }
      break;
    case Event::ON_RELEASING:
      if(!m_keys[event.component])
      {
        magnitude=1;
        return true;
      }
      break;
  }

  return false;
}
